package org.demo.config;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.io.resource.ResourceUtil;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.HashUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.alibaba.druid.pool.DruidDataSource;
import com.hellokaton.anima.Anima;
import com.hellokaton.blade.Blade;
import com.hellokaton.blade.ioc.annotation.Bean;
import com.hellokaton.blade.ioc.annotation.Order;
import com.hellokaton.blade.loader.BladeLoader;
import jetbrick.util.codec.MD5Utils;
import lombok.SneakyThrows;
import org.demo.utils.MainfestUtil;

import java.io.File;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;

@Bean
@Order(1)
public class JDBCLoader implements BladeLoader {
    private static final String SQL_FILE_PATH = "classpath:niuniu-1.sql";
    private static final String SQL_MD5_NAME = "md5.txt";

    @SneakyThrows
    @Override
    public void load(Blade blade) {
        // 配置数据库
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName(blade.environment().getOrNull("jdbc.driver"));
        dataSource.setUrl(blade.environment().getOrNull("jdbc.url"));
        dataSource.setUsername(blade.environment().getOrNull("jdbc.username"));
        dataSource.setPassword(blade.environment().getOrNull("jdbc.password"));

//        Anima.open("jdbc:h2:file:./db/niuniutodo;FILE_LOCK=FS;PAGE_SIZE=1024;CACHE_SIZE=8192", "admin", "123456");
        Anima.open(dataSource);
        executeSqlFile(SQL_FILE_PATH);
    }

    private void executeSqlFile(String sqlFilePath) throws UnsupportedEncodingException {
        boolean hasExec = calcMd5(sqlFilePath);
        if (hasExec) {
            System.out.println(" SQL file has Executed : " + sqlFilePath);
        }else {
            try {
                InputStream inputStream = ResourceUtil.getStream(sqlFilePath);
                String sql = IoUtil.read(inputStream, CharsetUtil.UTF_8);
                Anima.execute(sql);
                System.out.println("Executed SQL file: " + sqlFilePath);
                //记录md5,写入md5.txt
                File md5File = FileUtil.touch(MainfestUtil.getRunPath().getParent() + FileUtil.FILE_SEPARATOR + "db" + FileUtil.FILE_SEPARATOR + SQL_MD5_NAME);
                FileUtil.writeString(String.valueOf(SecureUtil.md5(ResourceUtil.getResourceObj(sqlFilePath).getName())), md5File, CharsetUtil.UTF_8);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private boolean calcMd5(String sqlFilePath) throws UnsupportedEncodingException {
        String path=MainfestUtil.getRunPath().getParent()+FileUtil.FILE_SEPARATOR+"db"+FileUtil.FILE_SEPARATOR+SQL_MD5_NAME;
        boolean fileExist = FileUtil.isFile(FileUtil.file(path));
        if (!fileExist){
            FileUtil.touch(path);
        }
        String content = FileUtil.readString(path,CharsetUtil.UTF_8);
        String md5 = StrUtil.toString(SecureUtil.md5(ResourceUtil.getResourceObj(sqlFilePath).getName()));
        //如果文件md5值和数据库中一致，则不执行sql文件
        return StrUtil.equals(content,md5);
    }
}
